package net.yla.smartbus.module.ba.employee.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.vip.vjtools.vjkit.collection.ListUtil;
import lombok.SneakyThrows;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.base.PageBean;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.DtoUtils;
import net.yla.smartbus.core.util.ExcelData;
import net.yla.smartbus.core.util.ExcelUtils;
import net.yla.smartbus.core.util.UploadExcelData;
import net.yla.smartbus.module.ba.area.entity.Areas;
import net.yla.smartbus.module.ba.area.mapper.AreasMapper;
import net.yla.smartbus.module.ba.dept.mapper.DeptMapper;
import net.yla.smartbus.module.ba.duty.mapper.DutyMapper;
import net.yla.smartbus.module.ba.employee.entity.EmployeeDO;
import net.yla.smartbus.module.ba.employee.entity.EmployeeEntity;
import net.yla.smartbus.module.ba.employee.mapper.EmployeeMapper;
import net.yla.smartbus.module.ba.employee.query.EmployeeQuery;
import net.yla.smartbus.module.ba.employee.service.EmployeeService;
import net.yla.smartbus.module.ba.group.entity.GroupEntity;
import net.yla.smartbus.module.ba.group.mapper.GroupMapper;
import net.yla.smartbus.module.ba.group.util.Spelling;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: Yee
 * @date: 2021/6/17 14:52
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    DeptMapper deptMapper;
    @Autowired
    DutyMapper dutyMapper;
    @Autowired
    AreasMapper areasMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    private UploadExcelData uploadExcelData;

    /**
     * 查询符合条件员工的记录集
     *
     * @param query
     * @return
     */
    @Override
    public PageBean<EmployeeEntity> findEmp(EmployeeQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize(), "empId desc");

        List<EmployeeDO> employeeDOS = employeeMapper.findEmp(query);
        if (ListUtil.isEmpty(employeeDOS)) {
            return new PageBean<>(ListUtil.emptyList(), query.getPageNum(), query.getPageSize(), 0);
        }
        int count = employeeMapper.countEmp(query);
        List<EmployeeEntity> employeeEntities = new ArrayList<>();
        for (EmployeeDO employeeDO : employeeDOS) {
            EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.setEmpId(employeeDO.getEmpId());
            employeeEntity.setGroupId(employeeDO.getGroupId());
            employeeEntity.setDeptId(employeeDO.getDeptId());
            employeeEntity.setVehicleId(employeeDO.getVehicleId());
            employeeEntity.setEmplyeeType(employeeDO.getEmplyeeType());
            employeeEntity.setName(employeeDO.getName());
            employeeEntity.setPinyin(employeeDO.getPinyin());
            employeeEntity.setAbbr(employeeDO.getAbbr());
            employeeEntity.setCode(employeeDO.getCode());
            employeeEntity.setCardNo(employeeDO.getCardNo());
            employeeEntity.setGender(employeeDO.getGender());
            employeeEntity.setDateOfBirth(employeeDO.getDateOfBirth());
            employeeEntity.setDriverLicense(employeeDO.getDriverLicense());
            employeeEntity.setCertificate(employeeDO.getCertificate());
            employeeEntity.setLicenseNo1(employeeDO.getLicenseNo1());
            employeeEntity.setLicenseNo2(employeeDO.getLicenseNo2());
            employeeEntity.setLicenseNo3(employeeDO.getLicenseNo3());
            employeeEntity.setLicenseNo4(employeeDO.getLicenseNo4());
            employeeEntity.setLicenseNo5(employeeDO.getLicenseNo5());
            employeeEntity.setRegisteredDate1(employeeDO.getRegisteredDate1());
            employeeEntity.setRegisteredDate2(employeeDO.getRegisteredDate2());
            employeeEntity.setRegisteredDate3(employeeDO.getRegisteredDate3());
            employeeEntity.setRegisteredDate4(employeeDO.getRegisteredDate4());
            employeeEntity.setRegisteredDate5(employeeDO.getRegisteredDate5());
            employeeEntity.setExpiryDate1(employeeDO.getExpiryDate1());
            employeeEntity.setExpiryDate2(employeeDO.getExpiryDate2());
            employeeEntity.setExpiryDate3(employeeDO.getExpiryDate3());
            employeeEntity.setExpiryDate4(employeeDO.getExpiryDate4());
            employeeEntity.setExpiryDate5(employeeDO.getExpiryDate5());
            employeeEntity.setImage1(employeeDO.getImage1());
            employeeEntity.setImage2(employeeDO.getImage2());
            employeeEntity.setImage3(employeeDO.getImage3());
            employeeEntity.setImage4(employeeDO.getImage4());
            employeeEntity.setImage5(employeeDO.getImage5());
            employeeEntity.setImage6(employeeDO.getImage6());
            employeeEntity.setImage7(employeeDO.getImage7());
            employeeEntity.setImage8(employeeDO.getImage8());
            employeeEntity.setImage9(employeeDO.getImage9());
            employeeEntity.setImage10(employeeDO.getImage10());
            employeeEntity.setIdCard(employeeDO.getIdCard());
            employeeEntity.setTel(employeeDO.getTel());
            employeeEntity.setPhone(employeeDO.getPhone());
            employeeEntity.setWorkUnit(employeeDO.getWorkUnit());
            employeeEntity.setNative1(employeeDO.getNative1());
            employeeEntity.setNation(employeeDO.getNation());
            employeeEntity.setEducation(employeeDO.getEducation());
            employeeEntity.setLocation(employeeDO.getLocation());
            employeeEntity.setDomicile(employeeDO.getDomicile());
            employeeEntity.setRegionalism(employeeDO.getRegionalism());
            employeeEntity.setMarriage(employeeDO.getMarriage());
            employeeEntity.setEnglishLevel(employeeDO.getEnglishLevel());
            employeeEntity.setPostalcode(employeeDO.getPostalcode());
            employeeEntity.setEmail(employeeDO.getEmail());
            employeeEntity.setAddress(employeeDO.getAddress());
            employeeEntity.setRemarks(employeeDO.getRemarks());

            //分组
            GroupEntity group = groupMapper.getGroup(employeeDO.getGroupId());
            if (group == null) {
                employeeEntity.setGroupName("--");
            } else {
                employeeEntity.setGroupName(group.getName());
            }

            //部门
            String deptName = deptMapper.deptName(employeeDO.getDeptId());
            if (deptName == null) {
                employeeEntity.setDeptName("--");
            } else {
                employeeEntity.setDeptName(deptName);
            }

            //职务
            String dutyName = dutyMapper.dutyName(employeeDO.getDutieId());
            if (dutyName == null) {
                employeeEntity.setDutyName("--");
            } else {
                employeeEntity.setDutyName(dutyName);
            }

            //学历
            Integer education = employeeDO.getEducation();
            if (education == 0) {
                employeeEntity.setEduName("未设置");
            } else if (education == 1) {
                employeeEntity.setEduName("小学");
            } else if (education == 2) {
                employeeEntity.setEduName("初中");
            } else if (education == 3) {
                employeeEntity.setEduName("高中");
            } else if (education == 4) {
                employeeEntity.setEduName("大专");
            } else if (education == 5) {
                employeeEntity.setEduName("本科");
            } else if (education == 6) {
                employeeEntity.setEduName("硕士");
            } else if (education == 7) {
                employeeEntity.setEduName("博士");
            }

            //籍贯
            String nativeName = areasMapper.nativeName(employeeDO.getNative1());
            employeeEntity.setNativeName(nativeName);


            employeeEntities.add(employeeEntity);

        }
        return new PageBean<>(employeeEntities, query.getPageNum(), query.getPageSize(), count);
    }

    /**
     * 逻辑删除人员
     *
     * @param personIds
     * @return
     */
    @Override
    public int delPersons(List<Integer> personIds) {
        if (personIds.size() == 0) {
            throw new AppException("请选择要删除的人员", RequestCode.forbid_error);
        } else {
            for (Integer empId : personIds) {
                int i = employeeMapper.delPersons(empId);
                if (i < 0) {
                    throw new AppException("删除失败", RequestCode.forbid_error);
                }
            }
        }
        return 1;
    }


    /**
     * 编辑人员信息
     *
     * @param employeeDto
     * @return
     */
    @SneakyThrows
    @Override
    public int editPerson(HttpServletRequest request, EmployeeEntity employeeDto) {
        if (employeeDto.getName() == null || employeeDto.getAbbr() == null || employeeDto.getPinyin() == null) {
            throw new AppException("员工姓名、拼音、缩拼不能为空！", 410);
        }
        if (employeeDto.getTel() != null) {
            if (employeeDto.getTel().length() > 11) {
                throw new AppException("办公电话格式不对", RequestCode.forbid_error);
            }
        }
        if (employeeDto.getPhone() != null) {
            if (employeeDto.getPhone().length() > 11) {
                throw new AppException("移动电话格式不对", RequestCode.forbid_error);
            }
        }
        if (employeeDto.getNativeName() == null) {
            employeeDto.setNative1(0);
        } else {
            Integer areaId = areasMapper.getArea(employeeDto.getNativeName());
            if (areaId == null) {
                Areas areas = new Areas();
                areas.setName(employeeDto.getNativeName());
                areas.setPinyin(Spelling.pinyin(employeeDto.getNativeName()));
                areas.setAbbr(Spelling.abbr(employeeDto.getNativeName()));
                areas.setQualifiedName(employeeDto.getNativeName());
                areasMapper.addAreas(areas);
                employeeDto.setNative1(areas.getAreaId());
            } else {
                employeeDto.setNative1(areaId);
            }
        }
        JSONObject jsonObject = DtoUtils.asDtoJsonForAll(employeeDto);
        EmployeeDO employeeDO = JSON.toJavaObject(jsonObject, EmployeeDO.class);
        employeeDO.setNative1(employeeDto.getNative1());
        List<String> images = employeeDto.getImages();
        if (images != null && images.size() != 0) {
            //因为不知道img集合的大小 这里利用反射对img进行赋值
            String[] methods = {"setImage1", "setImage2", "setImage3", "setImage4", "setImage5"};
            for (int i = 0; i < images.size(); i++) {
                Class clazz = employeeDO.getClass();
                try {
                    Method method = clazz.getMethod(methods[i], String.class);
                    method.invoke(employeeDO, images.get(i));
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        if (employeeDto.getEmpId() == null) {
            if (employeeMapper.employeeCradNo(employeeDto.getCardNo()) > 0) {
                throw new AppException("该员工卡号已存在", 410);
            } else if (employeeMapper.employeeCode(employeeDto.getCode()) > 0) {
                throw new AppException("该员工工号已存在", 410);
            } else {
                int i = employeeMapper.insertEmp(employeeDO);
                if (i < 0) {
                    throw new AppException("新增失败", RequestCode.forbid_error);
                }
            }
        } else {
            int i = employeeMapper.updateEmp(employeeDO);
            if (i < 0) {
                throw new AppException("修改失败", RequestCode.forbid_error);
            }
        }

        return 1;
    }

    /**
     * 导出人员信息
     *
     * @param response
     * @param query
     */
    @Override
    public void exportEmployees(HttpServletResponse response, EmployeeQuery query) {
        List<EmployeeEntity> list = this.findEmps(query);
        ExcelData data = new ExcelData();
        data.setName("人员信息");
        List<String> titles = new ArrayList();
        titles.add("姓名");
        titles.add("员工工号");
        titles.add("性别");
        titles.add("机构名称");
        titles.add("部门名称");
        titles.add("职务名称");
        titles.add("联系方式");
        titles.add("籍贯");
        /*titles.add("首发是否准点");*/
        /*titles.add("站点准点率");*/
        titles.add("民族");
        titles.add("学历");
        titles.add("出生日期");
        titles.add("从业时间");
        titles.add("通讯地址");
        titles.add("邮箱");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList<>();
        List<Object> row = null;
        if (ListUtil.isNotEmpty(list)) {
            for (EmployeeEntity dto : list) {
                row = new ArrayList<>();
                String sex = null;
                //性别
                if (dto.getGender() == 0) {
                    sex = "--";
                } else if (dto.getGender() == 1) {
                    sex = "男";
                } else if (dto.getGender() == 2) {
                    sex = "女";
                }
                //民族
                String[] nations = {"未设置", "汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族", "满族", "侗族", "瑶族", "白族",
                        "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "傈僳族", "佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族",
                        "达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族", "塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族",
                        "德昂族", "保安族", "裕固族", "京族", "塔塔尔族", "独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族"};
                String nation = null;
                for (int i = 0; i < nations.length; i++) {
                    if (dto.getNation() == i) {
                        nation = nations[i];
                    }
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                String dateOfBirth = dateFormat.format(dto.getDateOfBirth());
                String dateOfWork = dateFormat.format(dto.getDateOfWork());
                row.add(dto.getName() == null ? "--" : dto.getName());
                row.add(dto.getCardNo() == null ? "--" : dto.getCardNo());
                row.add(sex == null ? "--" : sex);
                row.add(dto.getGroupName() == null ? "--" : dto.getGroupName());
                row.add(dto.getDeptName() == null ? "--" : dto.getDeptName());
                row.add(dto.getDutyName() == null ? "--" : dto.getDutyName());
                row.add(dto.getPhone() == null ? "--" : dto.getPhone());
                row.add(dto.getNativeName() == null ? "--" : dto.getNativeName());
                row.add(nation == null ? "--" : nation);
                row.add(dto.getEduName() == null ? "--" : dto.getEduName());
                row.add(dateOfBirth == null ? "--" : dateOfBirth);
                row.add(dateOfWork == null ? "--" : dateOfWork);
                row.add(dto.getAddress() == null ? "--" : dto.getAddress());
                row.add(dto.getEmail() == null ? "--" : dto.getEmail());
                rows.add(row);
            }
        }
        data.setRows(rows);
        String fileName = "人员信息";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        fileName = fileName + "_" + dateFormat.format(new Date()) + ".xlsx";
        ExcelUtils.exportExcel(response, fileName, data);
    }

    /**
     * 导出中查询符合条件员工的记录集
     *
     * @param query
     * @return
     */
    public List<EmployeeEntity> findEmps(EmployeeQuery query) {

        List<EmployeeDO> employeeDOS = employeeMapper.findEmp(query);
        List<EmployeeEntity> employeeEntities = new ArrayList<>();
        for (EmployeeDO employeeDO : employeeDOS) {
            EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.setEmpId(employeeDO.getEmpId());
            employeeEntity.setGroupId(employeeDO.getGroupId());
            employeeEntity.setDeptId(employeeDO.getDeptId());
            employeeEntity.setVehicleId(employeeDO.getVehicleId());
            employeeEntity.setEmplyeeType(employeeDO.getEmplyeeType());
            employeeEntity.setName(employeeDO.getName());
            employeeEntity.setPinyin(employeeDO.getPinyin());
            employeeEntity.setAbbr(employeeDO.getAbbr());
            employeeEntity.setCode(employeeDO.getCode());
            employeeEntity.setCardNo(employeeDO.getCardNo());
            employeeEntity.setGender(employeeDO.getGender());
            employeeEntity.setDateOfBirth(employeeDO.getDateOfBirth());
            employeeEntity.setDriverLicense(employeeDO.getDriverLicense());
            employeeEntity.setCertificate(employeeDO.getCertificate());
            employeeEntity.setLicenseNo1(employeeDO.getLicenseNo1());
            employeeEntity.setLicenseNo2(employeeDO.getLicenseNo2());
            employeeEntity.setLicenseNo3(employeeDO.getLicenseNo3());
            employeeEntity.setLicenseNo4(employeeDO.getLicenseNo4());
            employeeEntity.setLicenseNo5(employeeDO.getLicenseNo5());
            employeeEntity.setRegisteredDate1(employeeDO.getRegisteredDate1());
            employeeEntity.setRegisteredDate2(employeeDO.getRegisteredDate2());
            employeeEntity.setRegisteredDate3(employeeDO.getRegisteredDate3());
            employeeEntity.setRegisteredDate4(employeeDO.getRegisteredDate4());
            employeeEntity.setRegisteredDate5(employeeDO.getRegisteredDate5());
            employeeEntity.setExpiryDate1(employeeDO.getExpiryDate1());
            employeeEntity.setExpiryDate2(employeeDO.getExpiryDate2());
            employeeEntity.setExpiryDate3(employeeDO.getExpiryDate3());
            employeeEntity.setExpiryDate4(employeeDO.getExpiryDate4());
            employeeEntity.setExpiryDate5(employeeDO.getExpiryDate5());
            employeeEntity.setImage1(employeeDO.getImage1());
            employeeEntity.setImage2(employeeDO.getImage2());
            employeeEntity.setImage3(employeeDO.getImage3());
            employeeEntity.setImage4(employeeDO.getImage4());
            employeeEntity.setImage5(employeeDO.getImage5());
            employeeEntity.setImage6(employeeDO.getImage6());
            employeeEntity.setImage7(employeeDO.getImage7());
            employeeEntity.setImage8(employeeDO.getImage8());
            employeeEntity.setImage9(employeeDO.getImage9());
            employeeEntity.setImage10(employeeDO.getImage10());
            employeeEntity.setIdCard(employeeDO.getIdCard());
            employeeEntity.setTel(employeeDO.getTel());
            employeeEntity.setPhone(employeeDO.getPhone());
            employeeEntity.setWorkUnit(employeeDO.getWorkUnit());
            employeeEntity.setNative1(employeeDO.getNative1());
            employeeEntity.setNation(employeeDO.getNation());
            employeeEntity.setEducation(employeeDO.getEducation());
            employeeEntity.setLocation(employeeDO.getLocation());
            employeeEntity.setDomicile(employeeDO.getDomicile());
            employeeEntity.setRegionalism(employeeDO.getRegionalism());
            employeeEntity.setMarriage(employeeDO.getMarriage());
            employeeEntity.setEnglishLevel(employeeDO.getEnglishLevel());
            employeeEntity.setPostalcode(employeeDO.getPostalcode());
            employeeEntity.setEmail(employeeDO.getEmail());
            employeeEntity.setAddress(employeeDO.getAddress());
            employeeEntity.setRemarks(employeeDO.getRemarks());

            //分组
            GroupEntity group = groupMapper.getGroup(employeeDO.getGroupId());
            if (group == null) {
                employeeEntity.setGroupName("--");
            } else {
                employeeEntity.setGroupName(group.getName());
            }

            //部门
            String deptName = deptMapper.deptName(employeeDO.getDeptId());
            if (deptName == null) {
                employeeEntity.setDeptName("--");
            } else {
                employeeEntity.setDeptName(deptName);
            }

            //职务
            String dutyName = dutyMapper.dutyName(employeeDO.getDutieId());
            if (dutyName == null) {
                employeeEntity.setDutyName("--");
            } else {
                employeeEntity.setDutyName(dutyName);
            }

            //学历
            Integer education = employeeDO.getEducation();
            if (education == 0) {
                employeeEntity.setEduName("未设置");
            } else if (education == 1) {
                employeeEntity.setEduName("小学");
            } else if (education == 2) {
                employeeEntity.setEduName("初中");
            } else if (education == 3) {
                employeeEntity.setEduName("高中");
            } else if (education == 4) {
                employeeEntity.setEduName("大专");
            } else if (education == 5) {
                employeeEntity.setEduName("本科");
            } else if (education == 6) {
                employeeEntity.setEduName("硕士");
            } else if (education == 7) {
                employeeEntity.setEduName("博士");
            }

            //籍贯
            String nativeName = areasMapper.nativeName(employeeDO.getNative1());
            employeeEntity.setNativeName(nativeName);


            employeeEntities.add(employeeEntity);

        }
        return employeeEntities;
    }


    /**
     * 导出人员模板
     *
     * @param response
     */
    @Override
    public void exportPersonTemplate(HttpServletResponse response) {
        ExcelData data = new ExcelData();
        data.setName("人员信息模板");
        List<String> titles = new ArrayList();
        titles.add("机构名称");
        titles.add("部门名称");
        titles.add("职务名称");
        titles.add("人员类型");
        titles.add("人员姓名");
        titles.add("性别");
        titles.add("员工工号(不可重复)");
        titles.add("员工卡号(不可重复)");
        titles.add("出生日期");
        titles.add("移动电话");

        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList<>();
        List<Object> row = null;
        row = new ArrayList<>();
        row.add("逸路安公交");
        row.add("软件部");
        row.add("普通职员");
        row.add("常规人员或驾驶员");
        row.add("张三");
        row.add("男");
        row.add("001");
        row.add("002");
        row.add("2021/05/31");
        row.add("18636568596");
        rows.add(row);
        data.setRows(rows);
        String fileName = "人员信息模板";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        fileName = fileName + "_" + dateFormat.format(new Date()) + ".xlsx";
        ExcelUtils.exportExcel(response, fileName, data);
    }

    @Override
    public int uploadPerson(HttpServletRequest request, MultipartFile file) {
        List<EmployeeEntity> list = uploadExcelData.readPersonExcel(file);
        for (EmployeeEntity form : list) {
            this.editPerson(request, form);
        }
        return 0;
    }

}
